﻿using DFGK.WMS.Common.Tools;
using DFGK.WMS.Common.Web;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.Controllers.Result;
using DFGK_WMS.WebAPI.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.WebAPI.Controllers.设备
{
    /// <summary>
    /// 输送线
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PipeLineController : ControllerBase
    {
        public ITPutawayOrderRepository TPutawayOrderService { get; set; }

        public ITCellRepository TCellRepository { get; set; }

        private readonly ILogRepository logRepository;

        private readonly WebSocketConnectManager socketManager;
        public PipeLineController(ITPutawayOrderRepository tPutawayOrderRepository, ITCellRepository tCellRepository, ILogRepository logRepository, WebSocketConnectManager socketConnectManager)
        {
            TPutawayOrderService = tPutawayOrderRepository;
            TCellRepository = tCellRepository;
            this.logRepository = logRepository;
            this.socketManager = socketConnectManager;
        }
        /// <summary>
        /// 输送线出入库任务状态上报
        /// </summary>
        /// <param name="putdto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult TaskAppear(PipeLineDto putdto)
        {
            if (putdto.method != "end")
            {
                return Ok(BaseResult.ReturnInfo(1, "任务未结束", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            var order = TPutawayOrderService.Getputawayorder(x => x.Code == putdto.taskCode);
            if (order == null)
            {
                return Ok(BaseResult.ReturnInfo(1, "未能找到任务", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            string message = "";
            //输送线任务完成
            if (putdto.method == "end")
            {
                //入库任务
                if (order.SourceType == 1)
                {
                    //堆垛机入库
                    //var data = new { taskCode = order.Code, taskType = order.SourceType, startPoint = putdto.roadwayCode, endPoint = order.LocationCode };
                    TaskLiku data = new TaskLiku()
                    {
                        taskCode = order.Code,
                        taskType = order.SourceType.ToString(),
                        startPoint = putdto.roadwayCode,
                        endPoint = order.LocationCode
                    };
                    var wcsdata = HttpHelper.WCSSendPostRequest("Api/ApiWCS/ReceiveTask", data);
                    LogHelper.Info("agv:" + wcsdata);
                    TLog logg = new TLog();
                    logg.LogType = 1;
                    logg.ActionType = 4;
                    logg.ModuleName = "设备接口";
                    logg.UserName = "堆垛机";
                    logg.RealName = "堆垛机";
                    logg.UserId = 0;
                    logg.Description = wcsdata;
                    //获取前端IP地址

                    logRepository.AddTLod(logg);
                    return Ok(BaseResult.ReturnInfo(0, wcsdata, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                }
                //出库任务
                else if (order.SourceType == 2)
                {

                    //调用库存接口
                    //任务修改
                    //order.Status = 5;
                   
                    //if (!TPutawayOrderService.UpdatePutawayorder(order))
                    //{
                    //    return Ok(BaseResult.ReturnInfo(1, "任务修改失败", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                    //}
                    if (order.SiteCode == "1800")
                    {
                        //做判断调用agv接口
                        //var date = new { TaskID = order.Code, materialcode = order.MaterialCode, Palletcode = order.PalletBarcode, Fromside = order.SiteCode, Agvgroup = "Agvgroup", Priority = 1 };

                        var shipp = TPutawayOrderService.GetShippingLock(order.RelatedOrderDetailId);
                        var pallst = TPutawayOrderService.GetPalletmsg(shipp.Id,out message);
                        if (pallst.Count()==0)
                        {
                            return Ok(BaseResult.Result(1,  message, "500"));
                        }
                        AgvRequst agv = new AgvRequst()
                        {
                            taskCode = order.Code,
                            tasktype = order.SourceType.ToString(),
                            pickingNo = shipp.Mblnr,
                            pickingLineNumber = shipp.Mjahr,
                            DeliveryNo = shipp.OrderSn,
                            DeliveryLineNumber = shipp.PurOrderLineNo,
                            abnormalTitle = pallst.Count().ToString(),
                            Pallet = pallst
                        };
                        var agvdt = HttpHelper.AgvSendPostRequest("script-api/getTaskByWms", agv);
                        LogHelper.Info("agv:" + agvdt);
                        TLog logg = new TLog();
                        logg.LogType = 1;
                        logg.ActionType = 4;
                        logg.ModuleName = "设备接口";
                        logg.UserName = "agv";
                        logg.RealName = "agv";
                        logg.UserId = 0;
                        logg.Description = agvdt;
                        //获取前端IP地址

                        logRepository.AddTLod(logg);
                    }
                    var ip = LedipShow.Getledip(order.SourceType, order.Roadway);
                    HttpHelper.LedSendPostRequest(new { ip = ip, message = "中煤科工西安研究院\\n(集团)有限公司\\n欢迎领导莅临检查" });
                    bool result = TPutawayOrderService.HandleUnbindOfOutstorageEnd(order, out message);
                    if (!result)
                        return Ok(BaseResult.Result(false, "出库失败" + message, "500"));
                    
                    return Ok(BaseResult.ReturnInfo(0, "出库任务结束", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                }
            }
            return Ok(BaseResult.ReturnInfo(0, "", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }
        /// <summary>
        /// 输送线入库任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetPutTaskData(PutLineDto dto)
        {
            var order = TPutawayOrderService.Getputawayorder(x => x.PalletBarcode == dto.barCode && x.SourceType==1 && x.Status==4);
            if (order == null)
            {
                return Ok(BaseResult.ReturnInfo(1, "未能找到任务", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            var ip =LedipShow.Getledip(order.SourceType,order.Roadway);
            var start = order.SourceType == 1 ? "入库" : "出库";
            HttpHelper.LedSendPostRequest(new {ip=ip, message="物料号:"+order.MaterialCode+"\\n"+"托盘码"+order.PalletBarcode+"\\n"+"状态:"+ start+"\\n位置:"+order.LocationCode });
            var data = new { taskCode = order.Code, taskType = order.SourceType, barCode = order.PalletBarcode, endPoint=order.Roadway };
            return Ok(BaseResult.ReturnInfo(0, "",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),data));
        }
        /// <summary>
        /// 入库拣选
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PutChooseTask(PutChooseDto dto)
        {
            var data=HttpHelper.SendPostRequest("入库拣选", dto);
            LogHelper.Info("入库拣选："+data);
            return Ok(BaseResult.ReturnInfo(0, data, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }
        /// <summary>
        /// 出库任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult TaskOutData(TaskOutDto dto )
        {
            var data = HttpHelper.SendPostRequest("出库任务", dto);
            LogHelper.Info("出库任务：" + data);
            return Ok(BaseResult.ReturnInfo(0, data, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }

        /// <summary>
        /// 获取当前任务巷道节点
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetRoadwayCode(RoadwayCode code)
        {
            var data = HttpHelper.SendPostRequestes("获取巷道节点", code);
            LogHelper.Info("巷道节点" + data);
            return Ok(BaseResult.ReturnInfo(0, data.data, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }
        /// <summary>
        /// 切换输送线模式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult LinePatternCut(string type)
        {
            //输送线模式切换
            var data = HttpHelper.SendPostRequest("模式切换", new { type = type });
            TLog logg = new TLog();
            logg.LogType = 1;
            logg.ActionType = 4;
            logg.ModuleName = "模式切换接口";
            logg.UserName = "输送线";
            logg.RealName = "输送线";
            logg.UserId = 0;
            logg.Description = data;
            //获取前端IP地址

            logRepository.AddTLod(logg);
            //数字孪生模式切换
            socketManager.SendMsgToAllClients(JsonConvert.SerializeObject(new { type = 7, data = type }));
            if (!TPutawayOrderService.UpdateStationsLine(type))
            {
                return Ok(BaseResult.Result(false, "模式修改失败", "500"));
            }
            return Ok(BaseResult.ReturnInfo(0, "", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }

        /// <summary>
        /// 模式查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetLinePattern()
        {
            var station = TPutawayOrderService.GetLinemodel();
            if (station.Remark != null)
            {
                return Ok(BaseResult.Result(station.Remark, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询成功！", "200", 0));
        }
    }
}
